package Solution.problem092.ReverseLinkedList2;

import common.ListNode;
import org.junit.Test;

/**
 * @program Leetcode
 * @description:
 * @author: lishangsheng
 * @create: 2019/07/01 15:48
 */
public class BetterSolution {

    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode left = dummy;
        /*找到开始反转的点*/
        for (int i = 0; i < m - 1; i++) left = left.next;

        /*反转的头*/
        ListNode reversedHead = left.next;
        /*反转的尾*/
        ListNode reversedTail = reversedHead;

        ListNode node = reversedHead.next;


        for (int i = 0; i < n - m; i++) {
            ListNode temp = node.next;
            node.next = reversedHead;
            reversedHead = node;
            node = temp;
        }

        left.next = reversedHead;
        reversedTail.next = node;
        return dummy.next;
    }


    @Test
    public void test() {
        //1->2->3->4->5
        ListNode listNode1 = new ListNode(0);
        ListNode listNode2 = new ListNode(1);
        ListNode listNode3 = new ListNode(2);
        ListNode listNode4 = new ListNode(3);
        ListNode listNode5 = new ListNode(4);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode5;

        ListNode result = reverseBetween(listNode1, 2, 4);
        System.out.println(result.val);
    }
}
